package ua.maxicash.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ua.maxicash.service.AppService;
import ua.maxicash.service.ConfirmationService;
import ua.maxicash.vo.SystemUser;

@Controller
@RequestMapping("/validation")
public class ValidationController {

    private static final Logger logger = Logger.getLogger(ValidationController.class);

    @Autowired
    private AppService appService;

    @Autowired
    private ConfirmationService confirmationService;

    @RequestMapping("/checkEmail")
    @ResponseBody
    public String checkEmail(@RequestParam("email") String email) {

        if (appService.getSystemUserByEmail(email) == null) {
            return "true";
        } else {
            return "false";
        }
    }

    @RequestMapping("/changePassword")
	@ResponseBody
	public String changePassword(@RequestParam("oldpass") String oldPass,
			@RequestParam("newpass") String newPass,
			@RequestParam("confirmpass") String confirmPass) {

		User user = (User) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();

		PasswordEncoder encoder = new Md5PasswordEncoder();
		String oldPassword = encoder.encodePassword(oldPass, null);

		SystemUser su = appService.getSystemUserByEmail(user.getUsername());

		if (user.getPassword().equals(oldPassword)) {
			if (newPass.equals(confirmPass)) {
				su.setPassword(encoder.encodePassword(newPass, null));
				appService.saveSystemUser(su);
			} else {
				return " {\"isOk\" : false , \"message\" : \"New password does not match confirmation\" } ";
			}
		} else {
			return " {\"isOk\" : false , \"message\" : \"Old password does not match actual\" } ";
		}

		return " {\"isOk\" : true } ";

	}

    @RequestMapping("/checkEmailNotFree")
    @ResponseBody
    public String checkEmailNotFree(@RequestParam("email") String email) {

        if (appService.getSystemUserByEmail(email) == null) {
            return "false";
        } else {
            return "true";
        }
    }

    @RequestMapping("/rules")
    public String showRules() {
        return "rules";
    }

    @RequestMapping("/aboutUs")
       public String showAboutUs() {
           return "aboutUs";
       }

       @RequestMapping("/help")
       public String showHelp() {
           return "help";
       }


}
